<template>
  <el-card>
    <el-button type="primary" @click="toUserList">返回用户信息列表</el-button>
    <el-row :gutter="20" style="margin: 20px">
      <el-col :span="4">请选择地址（省市区）：</el-col>
      <el-col :span="4"><UserCascader @sendUserAddress="sendUserAddress"></UserCascader></el-col>
      <!-- <el-col :span="4"
        ><el-button type="primary" @click="handleClick">保存</el-button></el-col
      > -->
      <el-col :span="4">详细地址（街道等）:</el-col>
      <el-col :span="6"><el-input placeholder="请输入详细地址" v-model="searchAddress"/></el-col>
      <el-col :span="4"><el-button type="primary" @click="handleUpdate">查询行车路线</el-button></el-col>
    </el-row>

    <el-row :gutter="20" style="margin: 20px">
      <el-col :span="12">您当前所在位置：{{ locationAddress }}</el-col>
      <el-col :span="6">经度：{{ location.lng }}</el-col>
      <el-col :span="6">纬度：{{ location.lat }}</el-col>
    </el-row>
    <el-row :gutter="20" style="margin: 20px">
      <el-col :span="4">地图中心点经度：</el-col>
      <el-col :span="4"><el-input v-model.number="center.lng" /></el-col>
      <el-col :span="4">地图中心点纬度：</el-col>
      <el-col :span="4"><el-input v-model.number="center.lat" /></el-col>
      <el-col :span="4">调整地图缩放：</el-col>
      <el-col :span="4"><el-input-number size="small" v-model="zoom" :step="1"/></el-col>
    </el-row>
    <el-divider></el-divider>
    <baidu-map
      class="map"
      :center="center"
      :zoom="zoom"
      @ready="ready"
      :scroll-wheel-zoom="true"
      @moving="syncCenterAndZoom"
      @moveend="syncCenterAndZoom"
      @zoomend="syncCenterAndZoom"
    >
      <bm-driving
        v-if="endPoint.lat"
        :start="location"
        :end="endPoint"
        :auto-viewport="true"
        policy=""
        :panel="true"
        location="上海市"
      >
      </bm-driving>
      <!-- 比例尺-->
      <bm-scale anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-scale>
      <!--缩放控件-->
      <bm-navigation
        anchor="BMAP_ANCHOR_TOP_RIGHT"
        :offset="{ height: 50, width: 50 }"
      ></bm-navigation>
      <bm-map-type
        :map-types="['BMAP_NORMAL_MAP', 'BMAP_HYBRID_MAP']"
        anchor="BMAP_ANCHOR_TOP_RIGHT"
      ></bm-map-type>
      <!--城市列表-->
      <bm-city-list anchor="BMAP_ANCHOR_TOP_LEFT"></bm-city-list>
      <bm-geolocation
        anchor="BMAP_ANCHOR_BOTTOM_RIGHT"
        :showAddressBar="true"
        :autoLocation="true"
      ></bm-geolocation>
    </baidu-map>
  </el-card>
</template>

<script setup lang="ts">
import { reactive, ref, nextTick, watch } from "vue";
import { useGeocoder, usePoint } from "vue-baidu-map-3x";
import { ElNotification, ElMessage } from "element-plus";
import { ShowStatus } from "../types";
import type { usersItemModel } from "@/types";
import { EditUserInfoListApi, getUserInfoListApi } from "@/api/mock/userInfo";

// 自定义事件
const emits = defineEmits(["setShowStatus"]);
// 接收属性（用户行信息）
const props = defineProps<{
  userInfo: usersItemModel;
}>();
// 将用户信息进行响应式存储
const currentUserInfo = reactive<usersItemModel>(props.userInfo);

const center = ref({ lng: 121.254, lat: 31.0731 });
// 当前定位位置点 & 驾车导航起点
const location = ref({ lng: 121.254, lat: 31.0731 });
// 当前定位位置地址
const locationAddress = ref<string>("");
const zoom = ref(15);
// 搜索的文字地址
const searchAddress = ref<string>("");
// 驾车导航终点
const endPoint = ref<any>({});

// 用户选择的地址
const userAddress = ref<string>("");
// 用户的省市区信息保存
const province = ref<string>("");
const city = ref<string>("");
const area = ref<string>("");
const ready = ({ BMap, map }: any) => {
  //  对地图进行自定义操作
  // 获取当前的地理位置并保存在center坐标中
  let geolocation = new BMap.Geolocation();
  geolocation.getCurrentPosition(function (r: any) {
    if (this.getStatus() == BMAP_STATUS_SUCCESS) {
      let mk = new BMap.Marker(r.point);
      map.addOverlay(mk);
      map.panTo(r.point);
      // console.log(r.point.lng + "," + r.point.lat);
      // 保存中心点和location为当前坐标位置
      center.value = { lng: r.point.lng, lat: r.point.lat };
      location.value = { lng: r.point.lng, lat: r.point.lat };
    } else {
      console.warn("获取当前地理位置失败");
    }
  });
};

// 点击保存按钮后修改地图中心位置
// 点击按钮保存将用户选择的地址通过请求进行修改
const handleUpdate = async () => {
  if (userAddress.value.trim() === "") {
    ElMessage.error("请选择省市区!");
    return;
  }
  if (searchAddress.value.trim() === "") {
    ElMessage.error("请输入街道的详细地址!");
    return;
  }
  useGeocoder().then((geocoder: any) => {
    geocoder.getPoint(`${userAddress.value}${searchAddress.value}`, (res) => {
      center.value.lng = res.lng;
      center.value.lat = res.lat;
      endPoint.value = { lng: res.lng, lat: res.lat };
    });
  });
  ElNotification({
    title: "提示",
    message: "已为您规划行车路线",
    type: "success",
    position: "top-left",
  });
  // 发送请求修改用户地址
  await EditUserInfoListApi(currentUserInfo.id, {
    ...currentUserInfo,
    province: province.value,
    city: city.value,
    area: area.value,
    address: `${userAddress.value}${searchAddress.value}`,
  });
  ElMessage.success("保存地址成功");
};

// 缩放地图修改经纬度
const syncCenterAndZoom = (e: any) => {
  const { lng, lat } = e.target.getCenter();
  zoom.value = e.target.getZoom();
  nextTick(() => {
    center.value.lng = lng;
    center.value.lat = lat;
  });
};

// 接收用户选择的地址信息
const sendUserAddress = (val: any[]): void => {
  province.value = val[0];
  city.value = val[1];
  area.value = val[2];
  userAddress.value = val.join("");
};
// 返回用户列表
const toUserList = () => {
  emits("setShowStatus", ShowStatus.USER_LIST);
  getUserInfoListApi(1, 10);
};

// 监控坐标点位置，并返回坐标点位置的坐标地理位置（文字）
watch(
  location,
  (newVal) => {
    useGeocoder().then((geocoder: any) => {
      // usePoint 通过坐标值返回百度坐标点对象
      usePoint(newVal.lng, newVal.lat).then((point: any) => {
        geocoder.getLocation(point, (result: any) => {
          locationAddress.value = result.address;
        });
      });
    });
  },
  { deep: true, immediate: true }
);
</script>
<script lang="ts">
export default {
  name: "userDetail",
};
</script>
<style lang="scss">
.map {
  width: 90%;
  height: 500px;
  margin: 0 auto;
}
.el-col {
  display: inline-block;
}
</style>
